package org.water.config;

import org.apache.shiro.mgt.SecurityManager;
import org.apache.shiro.session.mgt.SessionManager;
import org.apache.shiro.session.mgt.eis.MemorySessionDAO;
import org.apache.shiro.session.mgt.eis.SessionDAO;
import org.apache.shiro.spring.LifecycleBeanPostProcessor;
import org.apache.shiro.spring.security.interceptor.AuthorizationAttributeSourceAdvisor;
import org.apache.shiro.spring.web.ShiroFilterFactoryBean;
import org.apache.shiro.web.mgt.DefaultWebSecurityManager;
import org.apache.shiro.web.servlet.SimpleCookie;
import org.apache.shiro.web.session.mgt.DefaultWebSessionManager;
import org.springframework.aop.framework.autoproxy.DefaultAdvisorAutoProxyCreator;
import org.springframework.boot.web.servlet.FilterRegistrationBean;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.filter.DelegatingFilterProxy;
import org.water.common.shiro.DefaultCredentialsMatcher;
import org.water.common.shiro.ShiroDbRealm;
import org.water.common.shiro.filter.ApiAuthFilter;
import org.water.common.shiro.filter.UserAuthenticationFilter;
import org.water.common.shiro.filter.UserPermissionsAuthorizationFilter;

import javax.servlet.Filter;
import java.util.HashMap;
import java.util.LinkedHashMap;
import java.util.Map;

/**
 * shiro管理
 * @author qzy
 *
 */
@Configuration
public class ShiroConfig {

	/**
	 * 用户授权认证
	 * @return
	 */
	@Bean("shiroDbRealm")
	public ShiroDbRealm shiroDbRealm(DefaultCredentialsMatcher pwdMatcher)
	{
		ShiroDbRealm shiroDbRealm=new ShiroDbRealm();
		shiroDbRealm.setCredentialsMatcher(pwdMatcher);
		return shiroDbRealm;
	}
	
	/**
	 * 密码匹配器
	 * @return
	 */
	@Bean("pwdMatcher")
	public DefaultCredentialsMatcher pwdMatcher()
	{
		DefaultCredentialsMatcher pwdMatcher=new DefaultCredentialsMatcher();
		return pwdMatcher;
	}
	/**
	 * shiro session 管理
	 * @return
	 */
	@Bean("sessionDAO")
	public MemorySessionDAO shiroSessionDao()
	{
		return new MemorySessionDAO();
	}
	@Bean("sessionIdCookie")
	public SimpleCookie sessionIdCookie()
	{
		SimpleCookie sessionIdCookie=new SimpleCookie("sid");
		sessionIdCookie.setHttpOnly(true);
		sessionIdCookie.setMaxAge(-1); //关闭浏览session就失效
		return sessionIdCookie;
	}
	
    @Bean("sessionManager")
    public SessionManager sessionManager(SessionDAO sessionDAO,SimpleCookie sessionIdCookie){
        DefaultWebSessionManager sessionManager = new DefaultWebSessionManager();
        sessionManager.setSessionValidationSchedulerEnabled(true);
        sessionManager.setSessionIdCookieEnabled(true);
        sessionManager.setSessionIdCookie(sessionIdCookie);
        sessionManager.setSessionDAO(sessionDAO);
        return sessionManager;
    }

    @Bean("securityManager")
    public SecurityManager securityManager(ShiroDbRealm shiroDbRealm, SessionManager sessionManager) {
        DefaultWebSecurityManager securityManager = new DefaultWebSecurityManager();
        securityManager.setRealm(shiroDbRealm);
        securityManager.setSessionManager(sessionManager);

        return securityManager;
    }

    /**
     * api认证
     * @return
     */
    @Bean("authFilter")
    public ApiAuthFilter authFilter()
    {
    	return new ApiAuthFilter();
    }
    /**
     * 用户登录认证
     * @return
     */
    @Bean("userAuthenticationFilter")
    public UserAuthenticationFilter userAuthenticationFilter()
    {
    	return new UserAuthenticationFilter();
    }
    /**
     * 用户权限认证
     * @return
     */
    @Bean("userPermissionsAuthorizationFilter")
    public UserPermissionsAuthorizationFilter userPermissionsAuthorizationFilter()
    {
    	return new UserPermissionsAuthorizationFilter();
    }
    
    @Bean("shiroFilter")
    public ShiroFilterFactoryBean shiroFilter(SecurityManager securityManager,ApiAuthFilter authFilter,UserAuthenticationFilter userAuthenticationFilter,UserPermissionsAuthorizationFilter userPermissionsAuthorizationFilter) {
        ShiroFilterFactoryBean shiroFilter = new ShiroFilterFactoryBean();
        shiroFilter.setSecurityManager(securityManager);
        shiroFilter.setLoginUrl("/shiro/login");
        shiroFilter.setUnauthorizedUrl("/shiro/unauthrorize");
        shiroFilter.setSuccessUrl("/shiro/sucess");
        //oauth过滤
        Map<String, Filter> filters = new HashMap<>();
        filters.put("api", authFilter);
        filters.put("formAuth", userAuthenticationFilter);
        filters.put("permissions", userPermissionsAuthorizationFilter);
        shiroFilter.setFilters(filters);

        Map<String, String> filterMap = new LinkedHashMap<>();
        filterMap.put("/shiro/**", "anon");
        filterMap.put("/error/**", "anon");
        filterMap.put("/static/**", "anon");
        filterMap.put("/favicon.ico", "anon");
        filterMap.put("/druid/**", "formAuth");
        filterMap.put("/admin/**", "formAuth,api");
//        filterMap.put("/**", "formAuth"); 
        shiroFilter.setFilterChainDefinitionMap(filterMap);
        return shiroFilter;
    }
    /**
     * shiro filter 代理
     * @return
     */
    @Bean("delegatingFilterProxy")
    public FilterRegistrationBean<Filter> delegatingFilterProxy(){
        FilterRegistrationBean<Filter> filterRegistrationBean = new FilterRegistrationBean<>();
        DelegatingFilterProxy proxy = new DelegatingFilterProxy();
        proxy.setTargetFilterLifecycle(true);
        proxy.setTargetBeanName("shiroFilter");
        filterRegistrationBean.setFilter(proxy);
        //filterRegistrationBean.addUrlPatterns("/*");
        //filterRegistrationBean.setOrder(0);
        return filterRegistrationBean;
    }
    
    @Bean("lifecycleBeanPostProcessor")
    public LifecycleBeanPostProcessor lifecycleBeanPostProcessor() {
        return new LifecycleBeanPostProcessor();
    }

    @Bean
    public DefaultAdvisorAutoProxyCreator defaultAdvisorAutoProxyCreator() {
        DefaultAdvisorAutoProxyCreator proxyCreator = new DefaultAdvisorAutoProxyCreator();
        proxyCreator.setProxyTargetClass(true);
        return proxyCreator;
    }

    @Bean
    public AuthorizationAttributeSourceAdvisor authorizationAttributeSourceAdvisor(SecurityManager securityManager) {
        AuthorizationAttributeSourceAdvisor advisor = new AuthorizationAttributeSourceAdvisor();
        advisor.setSecurityManager(securityManager);
        return advisor;
    }

}
